package com.link.play.fit.ai.ui.main

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.link.play.fit.ai.bean.BaseScanFoodBean
import com.link.play.fit.ai.bean.RecentlyEatenData
import com.link.play.fit.ai.ext.d
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.launch

class GlobalViewModel(application: Application) : AndroidViewModel(application) {

    // 单例实例
    companion object {
        @Volatile
        private var instance: GlobalViewModel? = null

        fun getInstance(application: Application): GlobalViewModel {
            return instance ?: synchronized(this) {
                instance ?: GlobalViewModel(application).also { instance = it }
            }
        }
    }

    // 使用 LiveData
    private val _mainRecentlySharedFlow = MutableLiveData<RecentlyEatenData>()
    val mainRecentlySharedFlow: LiveData<RecentlyEatenData> = _mainRecentlySharedFlow

    val recentlyEatenDataFlow: SharedFlow<RecentlyEatenData> get() = _recentlyEatenData
    private val _recentlyEatenData = MutableSharedFlow<RecentlyEatenData>(replay = 0)

    fun addRecentlyData(newData: RecentlyEatenData) {
        viewModelScope.launch {
            newData.notifyType=1 //添加
            _recentlyEatenData.emit(newData)
        }
    }

    fun deleteRecentlyData(delData: RecentlyEatenData) {
        viewModelScope.launch {
            delData.notifyType=2  //删除
            _recentlyEatenData.emit(delData)

        }
    }

    fun updateRecentlyData(delData: RecentlyEatenData) {
        viewModelScope.launch {
            delData.notifyType=3  //更新
            _recentlyEatenData.emit(delData)

        }
    }

    fun updateLiveData(newData: RecentlyEatenData) {
        _mainRecentlySharedFlow.value = newData
    }


}